package org.spider.core.job;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spider.api.context.SpiderContext;
import org.spider.api.utils.io.FileUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;


/**
 * 任务上下文，和任务的输出，文件写入有关
 */
@Data
public class SpiderJobContext extends SpiderContext {
    private OutputStream outputStream;
    //是否输出到文件
    private boolean output;
    private Object mutex = new Object();
    private OutputStream outputstream;
    static Logger logger= LoggerFactory.getLogger(SpiderJobContext.class);

    public SpiderJobContext(OutputStream outputstream,boolean output) {
        super();
        this.outputstream = outputstream;
        this.output = output;
    }

    public void close(){
        try {
            this.outputstream.close();
        } catch (Exception e) {
        }
    }

    public OutputStream getOutputstream(){
        return this.outputstream;
    }

    public static SpiderJobContext create(String directory,String id,Integer taskId,boolean output){
        OutputStream os = null;
        try {
            File file = FileUtils.getLogFile(directory,id,taskId);
            File dirFile = file.getParentFile();
            if(!dirFile.exists()){
                dirFile.mkdirs();
            }
            logger.info(file.getAbsolutePath());
            os = new FileOutputStream(file, true);
        } catch (Exception e) {
            logger.error("创建日志文件出错",e);
        }
        SpiderJobContext context = new SpiderJobContext(os, output);
        logger.info("当前Context id为:{}",context.getId());
        context.setFlowId(id);
        return context;
    }
}
